package com.quyeying.config.interceptor;

import com.quyeying.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName AdminInterceptor
 * @Description TODO
 * @Author skx
 * @Date 2020/11/26
 */
public class AdminInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    private final static String prefix = "JWT_TOKEN_";

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //统一拦截（验证是否带有token, token是否合法)
        String authorization = request.getHeader("Authorization");
        //测试标识不拦截
        if(StringUtils.isEmpty(authorization)) {
            returnJson(response,"{\"code\":403,\"msg\":\"非法请求!\"}");
            return false;
        }

        //验证token是否有效，是直接返回true
        if(JwtUtil.verity(authorization)) {
            return true;
        }
        //验证redis里是否存在refreshToken
        Object refreshToken = redisTemplate.opsForValue().get(prefix.concat(JwtUtil.getUserName(authorization)));
        if(!StringUtils.isEmpty(refreshToken) && refreshToken.equals(authorization)) {

            //刷新token
            String sign = JwtUtil.sign(JwtUtil.getUserName(authorization));
            redisTemplate.opsForValue().set(prefix.concat(JwtUtil.getUserName(authorization)), sign, 10080, TimeUnit.MINUTES);
            response.setHeader("Authorization", sign);
            return true;
        }

        returnJson(response,"{\"code\":403,\"msg\":\"登录失效!\"}");
        return false;
//        return false;//如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
        //如果设置为true时，请求将会继续执行后面的操作
    }

    /*返回客户端数据*/
    private void returnJson(HttpServletResponse response, String json) throws Exception{
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
//         System.out.println("执行了TestInterceptor的postHandle方法");
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//        System.out.println("执行了TestInterceptor的afterCompletion方法");
    }
}
